package com.yuyu.tt.controller;

import cn.hutool.core.util.RandomUtil;
import com.yuyu.tt.context.TenantContextHolder;
import com.yuyu.tt.domain.SysUser;
import com.yuyu.tt.exec.InheritableRequestTaskExecutor;
import com.yuyu.tt.service.SysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 深海鱼鱼
 * @version 1.0
 * @description:
 * @date 2024/11/20 11:22
 */
@RestController
@RequestMapping("/test")
@AllArgsConstructor
@Slf4j
public class SysUserController {

//    @Resource
//    private InheritableRequestTaskExecutor inheritableRequestTaskExecutor;

    private SysUserService sysUserService;

//    @GetMapping("/all")
//    public List<SysUser> all() {
//        return sysUserService.list();
//    }

//    @GetMapping("/save")
//    public String save() {
//        sysUserService.save(SysUser.builder()
//                .username(RandomUtil.randomString(8))
//                .password(RandomUtil.randomString(8))
//                .build());
//        return "操作成功";
//    }

    /**
     * 每次请求单开一个线程处理，速度尚可，但是实现逻辑不合理，没有考虑大量请求的情况
     * @param request
     * @return
     */
//    @GetMapping("/async")
//    public String async(HttpServletRequest request) {
//        String projectCode = request.getHeader("projectCode");
//        log.info("接收到projectCode: [{}]", projectCode);
//        TenantContextHolder.setProjectCode(projectCode);
//        sysUserService.saveUserByAsyncAnnotation();
//        TenantContextHolder.removeProjectCode();
//        return "异步执行，请查看是否成功";
//    }

    /**
     * 响应速度太慢 -> 使用线程池&使用servlet容器的异步上下文实现
     * @param request
     * @return
     */
//    @GetMapping("/async2")
//    public String async2(HttpServletRequest request) {
//        String projectCode = request.getHeader("projectCode");
//        log.info("接收到projectCode: [{}]", projectCode);
//        inheritableRequestTaskExecutor.execute(() -> {
//            sysUserService.saveUserByTaskExec();
//        });
//        return "异步执行，请查看是否成功";
//    }

    /**
     * 使用线程池装饰器实现异步子线程获取request数据
     * ==================================最优解==================================
     * 涉及类及其注释
     * RequestHeritableContextDecorator.java -> 请求上下文继承装饰器
     * TenantContextHolder.java -> 租户信息上下文线程局部变量缓存
     * MybatisPlusConfig.java -> mybatis-plus多租户插件配置类
     * ==================================最优解==================================
     *
     * @return
     */
    @GetMapping("/async3")
    public String async3() {
        sysUserService.saveUserByAsyncAnnotation2();
        return "异步执行，请查看是否成功";
    }

}
